﻿using Microsoft.EntityFrameworkCore;
using RepositoryTestWeb.Entity;
using System;
using System.Linq;

namespace RepositoryTestWeb.DbContext
{
    public class TestDbContext : Microsoft.EntityFrameworkCore.DbContext
    {
        public TestDbContext(DbContextOptions options) : base(options)
        {

        }



        /// <summary>
        /// 用户
        /// </summary>
        public DbSet<UserEntity> Users { get; set; }

        /// <summary>
        /// 日志
        /// </summary>
        public DbSet<LogEntity> Logs { get; set; }

        /// <summary>
        /// 订单
        /// </summary>
        public DbSet<OrderEntity> Orders { get; set; }

        /// <summary>
        /// 商品
        /// </summary>
        public DbSet<GoodsEntity> Goods { get; set; }


        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.ApplyConfiguration(new UserConfiguration());
            modelBuilder.ApplyConfiguration(new GoodsConfiguration());
            modelBuilder.ApplyConfiguration(new LogConfiguration());
            modelBuilder.ApplyConfiguration(new OrderConfiguration());

            base.OnModelCreating(modelBuilder);
        }
    }

    /// <summary>
    /// 初始化
    /// </summary>
    public static class TestDbContextInitialize
    {
        /// <summary>
        /// 数据自动迁移
        /// </summary>
        /// <param name="context"></param>
        public static void AutoMigration(this TestDbContext context)
        {
            if (true == context.Database.GetPendingMigrations().Any())
            {
                context.Database.Migrate();
            }
        }

        /// <summary>
        /// 写入种子数据
        /// </summary>
        /// <param name="context"></param>
        public static void EnsureSeedData(this TestDbContext context)
        {
            if (false == context.Users.Any())
            {
                var admin = new UserEntity
                {
                    UserName = "admin",
                    Password = "123456",
                    CreatorUserId = null,
                    CreationTime = DateTime.Now
                };

                context.Users.Add(admin);
                context.SaveChanges();
            }
        }
    }
}
